git commit msg格式规范校验

@[toc]

1. commit规范

每个公司的规范都是不同的,这里讲下我常用的规范
type(模块): message

type

用于说明 commit的类别,只允许使用下面7个标识。

  • feat:新功能(feature)
  • fix:修补bug
  • hotfix:紧急修复bug
  • test:增加测试
  • docs:文档(documentation)
  • style: 格式(不影响代码运行的变动)
  • refactor:重构(即不是新增功能,也不是修改bug的代码变动)
  • chore:构建过程或辅助工具的变动

举个例子,我新增了用户登录功能,那么提交信息应该这样写:

1
git commit -m "feat(user): add the user login"

2. 使用git hooks校验

.git/hooks目录下有很多钩子,我们可以根据需要自定义不同的内容,这里我们只需要修改commit-msg即可。

首先将commit-msg.sample 改为 commit-msg,也就是去掉后缀。
将里面的内容修改为下面内容

1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
MSG=`awk '{printf("%s",$0)}' $1`
if [[ $MSG =~ ^(feat|fix|test|refactor|docs|style|chroe)\(.*\):.*$ ]]
then
echo -e "\033[32m commit success! \033[0m"
else
echo -e "\033[31m Error: the commit message is irregular \033[m"
echo -e "\033[31m Error: type must be one of [feat,fix,docs,style,refactor,test,chore] \033[m"
echo -e "\033[31m eg: feat(user): add the user login \033[m"
exit 1
fi

当我们提交不规范的commit信息时就会提醒用户,并终止此提交

3. gitlab ci 中校验

3.1 .gitlab-ci.yml

1
2
3
4
5
6
7
8
9
stages:
- lint

commit_msg:
stage: lint
script:
- /bin/bash commit-msg.sh
only:
- pushes

3.2 commit-msg.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#! /bin/bash

# get commit msg
if [[ $CI_COMMIT_MESSAGE ]]; then
msg=$CI_COMMIT_MESSAGE
else
read msg < .git/COMMIT_EDITMSG
fi

echo -e "\033[33m The commit msg: \033[0m $msg"

# if the msg is merge then skip it
mergePattern='^Merge '
if [[ $msg =~ $mergeCommitPattern ]]; then
echo -e "\033[32m skip the merge, commit success! \033[0m"
exit 0
fi

# check the commit msg
maxLength=50
length=${#msg}
pattern='^(feat|fix|hotfix|test|refactor|docs|style|chroe)\(.*\):.*$'

if [[ $msg =~ $pattern ]]; then
if [[ $length -gt $maxLength ]]; then
echo -e "\033[31m Error: the msg over max length \033[m"
exit 1
fi
echo -e "\033[32m commit success! \033[0m"
else
echo -e "\033[31m Error: the commit message is irregular \033[m"
echo -e "\033[31m Error: type must be one of [feat,fix,hotfix,docs,style,refactor,test,chore] \033[m"
echo -e "\033[31m eg: feat(user): add the user login \033[m"
exit 1
fi
-------------本文结束感谢您的阅读-------------